import axios, {type AxiosResponse, type InternalAxiosRequestConfig} from 'axios'
import { message } from 'antd';
import qs from 'qs'

//创建的axios实例
const instance = axios.create({
    baseURL: 'http://www.bingo1440.top:21001',    //请求的基路径
    timeout: 10000                      //请求超时时间
})
//拦截器:对请求和响应做统一处理
//请求拦截器：对前端的所有请求做统一处理
instance.interceptors.request.use(
    (config: InternalAxiosRequestConfig): InternalAxiosRequestConfig<void> => {
        //获取token
        const token = JSON.parse(<string>localStorage.getItem('t_k'))
        if (token) {
            config.headers.Authorization = token
        }
        return config
    },
    (err: any) => {
        console.log('err', err)
        message.error('请求失败')
    })


//响应拦截器：对后端响应的结果做同一处理
instance.interceptors.response.use(
    (resp: AxiosResponse<unknown, unknown>) => {
        return resp
    },
    (err: { response: { data: { code: any; }; }; }) => {
        //处理网络异常
        if (err.response && err.response.data) {
            const code = err.response.data.code
            switch (code) {
                case 401:
                    message.warning('还未登录，请先登录')
                    break
                case 403:
                    message.warning('登录过期，请重新登录')
                    break
                case 404:
                    message.error('页面不存在')
                    break
                case 405:
                    message.error('方法不允许')
                    break
                case 408:
                    message.error('请求超时，请稍后再试')
                    break
                case 502:
                    message.error('网络错误')
                    break
                case 503:
                    message.error('服务不可用')
                    break
                case 504:
                    message.error('网络超时，请检查网络')
                    break
                // default:
                //   message.error('未知错误')
            }
        } else {
            message.error('响应失败')
        }
    }
)


/**
 * 对axios请求的基础封装
 */

const get = async (url: string, params: object = {}): Promise<AxiosResponse> => {
    return await instance.get(url, {params})
}

const post = async (url: string, data: object) => {
    return await instance.post(url, qs.stringify(data))
}

const put = async (url: string, data: object) => {
    return await instance.put(url, qs.stringify(data))
}

const del = async (url: string, params: object = {}) => {
    return await instance.delete(url, {params})
}

export default {
    get,
    post,
    put,
    del
}
